package cn.jhz.learn.community_dynamic.manager;

import java.io.ByteArrayInputStream;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import cn.jhz.learn.community_dynamic.model.ImageEntity;

@Service
public class FileManager {
    // Endpoint，其它Region请按实际情况填写。
    static private final String ENDPOINT = "http://oss-cn-shenzhen.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
    static private final String ACCESS_KEY_ID = "LTAI4G5zMLmV8tNAHBJSEkSf";
    static private final String ACCESS_KEY_SECRET = "UGyPlnDZBxxNGv0WPzLmtTtcyQmSYh";
    static private final String BUCKET_NAME = "machine005";
    static private final String FILE_SERVICE_ADDRESS = "https://machine005.oss-cn-shenzhen.aliyuncs.com/";
    /**
     * 1.先创建数据库实例,获取ID
     * 2.将ID作为唯一objectName上传
     * 3.
     */
    public String simpleByteUpload(byte[] content, String objectName) {
	// 创建OSSClient实例。
	OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
	ossClient.putObject(BUCKET_NAME, objectName, new ByteArrayInputStream(content));
	// 关闭OSSClient。
	ossClient.shutdown();
	
	return FILE_SERVICE_ADDRESS + objectName;
    }
    
//    public boolean deleteFile(String filePath) {
//	OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
//        boolean exist = ossClient.doesObjectExist(BUCKET_NAME, filePath);
//        if (!exist) {
//            LOGGER.error("文件不存在,filePath={}", filePath);
//            return false;
//        }
//        LOGGER.info("删除文件,filePath={}", filePath);
//        ossClient.deleteObject(bucketName, filePath);
//        ossClient.shutdown();
//        return true;
//    }

    @Transactional
    public ImageEntity updateInstanceColumn(ImageEntity entity, Byte status) {
	entity.setStatus(status);
	return entity;
    }
}
